package controller

import (
	"cloud-storage/global"
	"cloud-storage/model/mysql"
	"cloud-storage/utils"
	"cloud-storage/utils/response"
	"cloud-storage/utils/upload"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

// HandlerUpload 处理上传文件
func HandlerUpload(c *gin.Context) {
	phone := global.GetPhone(c)
	//获取用户信息
	user, err := mysql.GetUserInfo(phone)
	if err != nil {
		zap.L().Error("mysql.GetUserInfo() failed err:", zap.Error(err))
		response.ResponseError(c, response.CodeSelectOperationFail)
		return
	}
	fId := c.GetHeader("id")

	//接收上传文件
	_, head, err := c.Request.FormFile("file")
	if err != nil {
		zap.L().Error("c.Request.FormFile failed err:", zap.Error(err))
		response.ResponseError(c, response.CodeFileLoadingFail)
		return
	}
	//判断当前文件夹是否有同名软件
	if ok := mysql.CurrFileExists(fId, head.Filename); !ok {
		response.ResponseErrorWithMsg(c, response.CodeError, "文件已存在")
		return
	}
	//判断用户的容量是否足够
	if ok := mysql.CapacityIsEnough(head.Size, user.FileStoreId); !ok {
		response.ResponseErrorWithMsg(c, response.CodeError, "容量不够")
		return
	}
	fileHash := utils.EnCodeMD5(head.Filename)
	//通过hash判断文件是否已上传过oss
	if ok := mysql.FileOssExists(fileHash); ok {
		//上传至阿里云oss
		go upload.UploadOss(head, fileHash)
		//新建文件信息
		if err = mysql.CreateFile(head.Filename, fileHash, head.Size, fId, user.FileStoreId); err != nil {
			zap.L().Error("mysql.CreateFile() failed err:", zap.Error(err))
			response.ResponseError(c, response.CodeInsertOperationFail)
			return
		}

		//上传成功减去相应剩余容量
		err = mysql.SubtractSize(head.Size, user.FileStoreId)
		if err != nil {
			zap.L().Error("mysql.SubtractSize failed err:", zap.Error(err))
			response.ResponseError(c, response.CodeOperationFail)
			return
		}
		response.ResponseSuccess(c, nil)
	} else {
		response.ResponseErrorWithMsg(c, response.CodeError, "重复上传")
		return
	}

}
